package com.party.jackclientandroid.controller;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;

import com.party.jackclientandroid.R;
import com.party.jackclientandroid.BaseActivity;
import com.party.jackclientandroid.bean.ImageBean;
import com.party.jackclientandroid.permission.RuntimeRationale;
import com.party.jackclientandroid.photoselector.ui.PhotoSelector;
import com.party.jackclientandroid.utils.ConstUtils;
import com.party.jackclientandroid.utils.FileProvider7;
import com.party.jackclientandroid.utils.ImgUtil;
import com.party.jackclientandroid.utils.SDCardFileUtils;
import com.yalantis.ucrop.UCrop;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 选择照片控制器<br>
 */
public class ChoosePictureController extends BaseController {
    ArrayList<ImageBean> detailImgs = new ArrayList<>();
    LinkedBlockingQueue<String> mPhotoPathQueue = new LinkedBlockingQueue<>();
    boolean userTakePhoto;
    boolean userCrop;

    public ChoosePictureController(BaseActivity baseActivity) {
        super(baseActivity);
    }

    /**
     * 调用系统的拍照
     */
    public void handleTakePhoto() {
        userTakePhoto = true;
        checkCameraPermissions();
    }

    /**
     * 调用系统的拍照
     */
    private void handleTakePhotoWork() {
        String fileDir = SDCardFileUtils.getSDCardPath() + "AA_OperateApp/Camera/";
        SDCardFileUtils.creatDir2SDCard(fileDir);
        String fileName = DateFormat.format("yyyy_MM_dd_hh_mm_ss", new Date()) + ".jpg";
        File file = new File(fileDir, fileName);
        mPhotoPathQueue.offer(file.getAbsolutePath());
        Uri fileUri = FileProvider7.getUriForFile(baseActivity.get(), file);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        if (baseActivity.get() == null) return;
        baseActivity.get().startActivityForResult(intent, ConstUtils.RC_CAMERA);
    }

    /**
     * 清除掉之前选中图片
     */
    public void clearBeforeChoosePictures() {
        detailImgs.clear();
    }

    /**
     * 选择照片,可以裁剪的哟
     */
    public void handleToChooseCropPictures() {
        userCrop = true;
        if (detailImgs.size() == 0) {
            List<ImageBean> originDataList = baseActivity.get().getOriginDataList();
            if (originDataList != null && originDataList.size() > 0) {
                detailImgs.addAll(originDataList);
            }
        }
        ArrayList<String> urlList = new ArrayList<>();
        for (ImageBean ib : detailImgs) {
            // 只要本地文件
            if (!ib.getImgPath().startsWith("http:") && !ib.getImgPath().startsWith("https:")) {
                urlList.add(ib.getImgPath());
            }
        }
        int size = urlList.size();
        int index = -1;
        for (int i = 0; i < size; i++) {
            if (urlList.get(i).equals("")) {
                index = i;
                break;
            }
        }
        if (index != -1) {
            urlList.remove(index);
        }

        int size2 = detailImgs.size();
        int index2 = -1;
        for (int i = 0; i < size2; i++) {
            if (TextUtils.isEmpty(detailImgs.get(i).getImgPath())) {
                index2 = i;
                break;
            }
        }
        if (index2 != -1) {
            size2--;
        }
        PhotoSelector.builder()
                .setShowCamera(true)
                .setSelected(urlList)
                .setSingle(true)
                .setCrop(true)
                .setCropMode(PhotoSelector.CROP_RECTANG)
                .setGridColumnCount(ConstUtils.CHOOSE_PICTURE_COLUMN)
                .setMaterialDesign(false)
                .setToolBarColor(ContextCompat.getColor(baseActivity.get(), android.R.color.black))
                .setBottomBarColor(ContextCompat.getColor(baseActivity.get(), android.R.color.black))
                .setStatusBarColor(ContextCompat.getColor(baseActivity.get(), android.R.color.black))
                .start(baseActivity.get(), ConstUtils.RC_ALBUM);
    }

    /**
     * 选择照片
     */
    public void handleToChoosePictures(Object... objects) {
        if (detailImgs.size() == 0) {
            List<ImageBean> originDataList = baseActivity.get().getOriginDataList();
            if (originDataList != null && originDataList.size() > 0) {
                detailImgs.addAll(originDataList);
            }
        }
        ArrayList<String> urlList = new ArrayList<>();
        for (ImageBean ib : detailImgs) {
            // 只要本地文件
            if (!ib.getImgPath().startsWith("http:") && !ib.getImgPath().startsWith("https:")) {
                urlList.add(ib.getImgPath());
            }
        }
        int size = urlList.size();
        int index = -1;
        for (int i = 0; i < size; i++) {
            if (urlList.get(i).equals("")) {
                index = i;
                break;
            }
        }
        if (index != -1) {
            urlList.remove(index);
        }

        int size2 = detailImgs.size();
        int index2 = -1;
        for (int i = 0; i < size2; i++) {
            if (TextUtils.isEmpty(detailImgs.get(i).getImgPath())) {
                index2 = i;
                break;
            }
        }
        if (index2 != -1) {
            size2--;
        }
        int maxSelectCount = ConstUtils.CHOOSE_PICTURE_MAX_COUNT;
        try {
            if (objects != null && objects.length > 0) {
                maxSelectCount = (int) objects[0];
            }
        } catch (Exception e) {
        }
        PhotoSelector.builder()
                .setShowCamera(true)
                .setSelected(urlList)
                .setMaxSelectCount(maxSelectCount - size2 + urlList.size())
//                .setMaxSelectCount(1)
                .setGridColumnCount(ConstUtils.CHOOSE_PICTURE_COLUMN)
                .setMaterialDesign(false)
                .setToolBarColor(ContextCompat.getColor(baseActivity.get(), android.R.color.black))
                .setBottomBarColor(ContextCompat.getColor(baseActivity.get(), android.R.color.black))
                .setStatusBarColor(ContextCompat.getColor(baseActivity.get(), android.R.color.black))
                .start(baseActivity.get(), ConstUtils.RC_ALBUM);
    }

    /**
     * 选择完照片之后或者查看大图完之后更新数据到UI界面
     *
     * @param detailImgs
     */
    public void updateChoosePictures(List<ImageBean> detailImgs) {
        if (baseActivity.get() == null) return;
        baseActivity.get().updateChoosePictures(detailImgs);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 拍照处理
        if (resultCode == Activity.RESULT_OK && requestCode == ConstUtils.RC_CAMERA) {
            detailImgs.clear();
            ImageBean ib = new ImageBean();
            if (data == null) {
                ib.setImgPath(mPhotoPathQueue.poll());
            } else {
                ib.setImgPath(ImgUtil.getPhotoImagePath(baseActivity.get(), data));
            }
            detailImgs.add(ib);
            updateChoosePictures(detailImgs);
        }
        if (resultCode == Activity.RESULT_OK && data != null) {
            switch (requestCode) {
                case ConstUtils.RC_ALBUM:
                    if (userCrop) {
                        final Uri resultUri = UCrop.getOutput(data);
                        String img = ImgUtil.getImageAbsolutePath(baseActivity.get(), resultUri);
                        detailImgs.add(new ImageBean(img));
                        updateChoosePictures(detailImgs);
                        return;
                    }
                    ArrayList<String> images = data.getStringArrayListExtra(PhotoSelector.SELECT_RESULT);
                    // 删除之前存在的本地图片,比如之前选择了1,2,3;返回之后选择了1,2
                    ArrayList<ImageBean> tempLocalImages = new ArrayList<>();
                    for (ImageBean bean : detailImgs) {
                        if (!bean.getImgPath().startsWith("http:") || !bean.getImgPath().startsWith("https:")) {
                            if (!TextUtils.isEmpty(bean.getImgPath())) {
                                tempLocalImages.add(bean);
                            }
                        }
                    }
                    for (ImageBean bean : tempLocalImages) {
                        boolean contain = false;
                        for (String img : images) {
                            if (bean.getImgPath().equals(img)) {
                                contain = true;
                                break;
                            }
                        }
                        if (!contain) {
                            int size = detailImgs.size();
                            int index = -1;
                            for (int i = 0; i < size; i++) {
                                // 网络图片不删除
                                if (detailImgs.get(i).getImgPath().startsWith("http:") || detailImgs.get(i).getImgPath().startsWith("https:")) {
                                    continue;
                                }
                                if (bean.getImgPath().equals(detailImgs.get(i).getImgPath())) {
                                    index = i;
                                    break;
                                }
                            }
                            if (index != -1) {
                                detailImgs.remove(index);
                            }
                        }
                    }
                    // 添加之前没有的本地图片
                    for (String img : images) {
                        if (!containsPath(detailImgs, img)) {
                            detailImgs.add(new ImageBean(img));
                        }
                    }
                    int size = detailImgs.size();
                    int index = -1;
                    for (int i = 0; i < size; i++) {
                        if (TextUtils.isEmpty(detailImgs.get(i).getImgPath())) {
                            index = i;
                            break;
                        }
                    }
                    if (index != -1) {
                        detailImgs.remove(index);
                    }
                    if (detailImgs.size() < ConstUtils.CHOOSE_PICTURE_MAX_COUNT) {
                        detailImgs.add(new ImageBean());
                    }
                    updateChoosePictures(detailImgs);
                    break;
                case ConstUtils.IMAGE_DETAIL_CODE:
                    ArrayList<ImageBean> detailImages = (ArrayList<ImageBean>) data.getSerializableExtra("dataList");
                    detailImgs.clear();
                    detailImgs.addAll(detailImages);
                    if (detailImgs.size() < ConstUtils.CHOOSE_PICTURE_MAX_COUNT) {
                        detailImgs.add(new ImageBean());
                    }
                    updateChoosePictures(detailImgs);
                    break;
            }
        }
    }

    /**
     * 判断是否包含图片
     *
     * @param detailImgs
     * @param img
     * @return
     */
    public boolean containsPath(ArrayList<ImageBean> detailImgs, String img) {
        boolean contains = false;
        if (detailImgs != null) {
            for (ImageBean imageBean : detailImgs) {
                if (imageBean.getImgPath().equals(img)) {
                    contains = true;
                    break;
                }
            }
        }
        return contains;
    }

    /**
     * 检查拍照读取相册权限
     */
    public void checkCameraPermissions() {
        if (baseActivity.get() == null) return;
        final String[] permissions = new String[]{Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE};
        AndPermission.with(baseActivity.get())
                .runtime()
                .permission(permissions)
                .rationale(new RuntimeRationale())
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        Log.e("checkPermissions", "获取权限成功");
                        checkCameraPermissionsAgain(true, permissions);
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        Log.e("checkPermissions", "获取权限失败");
                        checkCameraPermissionsAgain(false, permissions);
                    }
                }).start();
    }

    /**
     * 用户点击不在提示,或者在应用管理里面关闭权限之后
     */
    public void checkCameraPermissionsAgain(boolean onGranted, String[] permissions) {
        if (baseActivity.get() == null) return;
        if (onGranted) {
            if (AndPermission.hasPermissions(baseActivity.get(), permissions)) {
                if (userTakePhoto) {
                    userTakePhoto = false;
                    handleTakePhotoWork();
                } else {
                    handleToChoosePictures();
                }
            } else {
                showSettingDialog(baseActivity.get(), permissions);
            }
        } else {
            if (AndPermission.hasAlwaysDeniedPermission(baseActivity.get(), permissions)) {
                showSettingDialog(baseActivity.get(), permissions);
            }
        }
    }

    /**
     * Display setting dialog.
     */
    public void showSettingDialog(Context context, final String[] permissions) {
        List<String> permissionNames = Permission.transformText(context, permissions);
        String message = context.getString(R.string.message_permission_always_failed, TextUtils.join("\n", permissionNames));

        new AlertDialog.Builder(baseActivity.get())
                .setCancelable(false)
                .setTitle(R.string.title_dialog)
                .setMessage(message)
                .setPositiveButton(R.string.setting, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toSystemSetting();
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }

    /**
     * 调整到系统设置界面去申请权限
     */
    public void toSystemSetting() {
        if (baseActivity.get() == null) return;
        AndPermission.with(baseActivity.get()).runtime().setting().start();
    }
}
